import asyncio
import logging
from datetime import datetime
from typing import Optional
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from services.shopify_service import shopify_service
from database.connection import get_session
import json

logger = logging.getLogger(__name__)


class SchedulerService:
    """定时任务服务，用于管理Shopify数据同步"""
    
    def __init__(self):
        self.scheduler = AsyncIOScheduler()
        self.is_running = False
        self.last_sync_time = None
        self.sync_status = {
            'orders': {'status': 'idle', 'last_success': None, 'error': None},
            'products': {'status': 'idle', 'last_success': None, 'error': None}
        }
    
    def start(self):
        """启动定时任务调度器"""
        if not self.is_running:
            try:
                # 添加订单同步任务 - 每30分钟执行一次
                self.scheduler.add_job(
                    self.sync_shopify_orders,
                    trigger=IntervalTrigger(minutes=30),
                    id='sync_shopify_orders',
                    name='从Shopify同步订单数据',
                    replace_existing=True
                )
                
                # 添加商品同步任务 - 每60分钟执行一次
                self.scheduler.add_job(
                    self.sync_shopify_products,
                    trigger=IntervalTrigger(minutes=60),
                    id='sync_shopify_products',
                    name='从Shopify同步商品数据',
                    replace_existing=True
                )
                
                # 启动调度器
                self.scheduler.start()
                self.is_running = True
                logger.info("定时任务调度器启动成功")
                logger.info("已添加Shopify订单同步任务 (每30分钟)")
                logger.info("已添加Shopify商品同步任务 (每60分钟)")
                
                # 立即执行一次同步（可选）
                asyncio.create_task(self.sync_all_shopify_data())
                
            except Exception as e:
                logger.error(f"启动定时任务调度器失败: {e}")
    
    def stop(self):
        """停止定时任务调度器"""
        if self.is_running:
            try:
                self.scheduler.shutdown()
                self.is_running = False
                logger.info("定时任务调度器已停止")
            except Exception as e:
                logger.error(f"停止定时任务调度器失败: {e}")
    
    async def sync_shopify_orders(self):
        """从Shopify同步订单数据"""
        logger.info("开始从Shopify同步订单数据...")
        self.sync_status['orders'] = {'status': 'syncing', 'last_success': None, 'error': None}
        
        try:
            # 获取同步的订单数据
            synced_orders = await shopify_service.sync_from_shopify()
            
            # 处理订单数据
            if synced_orders:
                # 使用异步会话处理数据库操作
                async with get_session() as session:
                    new_orders = 0
                    updated_orders = 0
                    
                    for shopify_order in synced_orders:
                        # 这里应该包含完整的订单处理逻辑
                        # 检查是否已存在，创建或更新订单记录
                        logger.info(f"处理Shopify订单: {shopify_order.get('id')} - {shopify_order.get('name')}")
                        # 实际的数据库操作应该在这里实现
                        
                    logger.info(f"Shopify订单同步完成: 新增 {new_orders}, 更新 {updated_orders}")
            
            self.sync_status['orders']['status'] = 'success'
            self.sync_status['orders']['last_success'] = datetime.now().isoformat()
            self.last_sync_time = datetime.now()
            
        except Exception as e:
            logger.error(f"从Shopify同步订单失败: {e}")
            self.sync_status['orders']['status'] = 'error'
            self.sync_status['orders']['error'] = str(e)
    
    async def sync_shopify_products(self):
        """从Shopify同步商品数据"""
        logger.info("开始从Shopify同步商品数据...")
        self.sync_status['products'] = {'status': 'syncing', 'last_success': None, 'error': None}
        
        try:
            # 获取同步的商品数据
            synced_products = await shopify_service.sync_products_from_shopify()
            
            # 处理商品数据
            if synced_products:
                # 使用异步会话处理数据库操作
                async with get_session() as session:
                    new_products = 0
                    updated_products = 0
                    
                    for shopify_product in synced_products:
                        # 这里应该包含完整的商品处理逻辑
                        # 检查是否已存在，创建或更新商品记录
                        logger.info(f"处理Shopify商品: {shopify_product.get('id')} - {shopify_product.get('title')}")
                        # 实际的数据库操作应该在这里实现
                        
                    logger.info(f"Shopify商品同步完成: 新增 {new_products}, 更新 {updated_products}")
            
            self.sync_status['products']['status'] = 'success'
            self.sync_status['products']['last_success'] = datetime.now().isoformat()
            self.last_sync_time = datetime.now()
            
        except Exception as e:
            logger.error(f"从Shopify同步商品失败: {e}")
            self.sync_status['products']['status'] = 'error'
            self.sync_status['products']['error'] = str(e)
    
    async def sync_all_shopify_data(self):
        """同步所有Shopify数据"""
        logger.info("开始同步所有Shopify数据...")
        
        # 并行执行订单和商品同步
        tasks = [
            self.sync_shopify_orders(),
            self.sync_shopify_products()
        ]
        
        await asyncio.gather(*tasks)
        logger.info("所有Shopify数据同步任务已提交")
    
    def get_status(self):
        """获取调度器状态信息"""
        jobs = []
        if self.is_running:
            jobs = [
                {
                    'id': job.id,
                    'name': job.name,
                    'next_run_time': job.next_run_time.isoformat() if job.next_run_time else None,
                    'trigger': str(job.trigger)
                }
                for job in self.scheduler.get_jobs()
            ]
        
        return {
            'is_running': self.is_running,
            'last_sync_time': self.last_sync_time.isoformat() if self.last_sync_time else None,
            'sync_status': self.sync_status,
            'active_jobs': jobs
        }


# 创建全局调度器实例
scheduler_service = SchedulerService()


def startup_event():
    """FastAPI启动事件，用于启动定时任务"""
    logger.info("FastAPI应用启动，初始化定时任务调度器...")
    scheduler_service.start()


def shutdown_event():
    """FastAPI关闭事件，用于停止定时任务"""
    logger.info("FastAPI应用关闭，停止定时任务调度器...")
    scheduler_service.stop()